package no.nordicsemi.android.nrfmesh.database.dao;

import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;

import java.util.List;

import no.nordicsemi.android.nrfmesh.database.entity.SentProfile;

@Dao
public interface SentProfileDao {

    // 插入发送配置
    @Insert
    void insertSentProfile(SentProfile profile);

    // 查询所有发送配置
    @Query("SELECT * FROM sent_profiles")
    List<SentProfile> getAllSentProfiles();

    // 根据 ID 查询某个发送配置
    @Query("SELECT * FROM sent_profiles WHERE id = :id LIMIT 1")
    SentProfile getSentProfileById(int id);

    // 删除发送配置
    @Delete
    void deleteSentProfile(SentProfile profile);

    @Query("SELECT * FROM sent_profiles ORDER BY id DESC")
    LiveData<List<SentProfile>> getAllProfilesLive();

    @Query("SELECT * FROM sent_profiles WHERE segmentDuration = :segmentDuration AND waveformType = :waveformType AND pulseWidth = :pulseWidth AND frequency = :frequency LIMIT 1")
    SentProfile findDuplicateProfile(int segmentDuration, String waveformType, int pulseWidth, int frequency);

    // 根据组ID查询所有段参数
    @Query("SELECT * FROM sent_profiles WHERE group_id = :groupId ORDER BY segment_index")
    List<SentProfile> getProfilesByGroupId(String groupId);

    // 根据组ID查询所有段参数（LiveData）
    @Query("SELECT * FROM sent_profiles WHERE group_id = :groupId ORDER BY segment_index")
    LiveData<List<SentProfile>> getProfilesByGroupIdLive(String groupId);

    // 删除整个组的所有段参数
    @Query("DELETE FROM sent_profiles WHERE group_id = :groupId")
    void deleteProfilesByGroupId(String groupId);

    // 查询所有唯一的组ID
    @Query("SELECT DISTINCT group_id FROM sent_profiles WHERE group_id IS NOT NULL ORDER BY group_id")
    LiveData<List<String>> getAllGroupIds();

    // 查询所有组配置（按组分组）
    @Query("SELECT * FROM sent_profiles WHERE group_id IS NOT NULL ORDER BY group_id, segment_index")
    LiveData<List<SentProfile>> getAllGroupedProfiles();

    // 检查配置名称是否重复
    @Query("SELECT COUNT(*) FROM sent_profiles WHERE config_name = :configName")
    int checkConfigNameExists(String configName);

    // 根据配置名称查询组配置
    @Query("SELECT * FROM sent_profiles WHERE config_name = :configName ORDER BY segment_index")
    List<SentProfile> getProfilesByConfigName(String configName);

    // 获取最新插入的配置（用于获取上一次使用的配置名称）
    @Query("SELECT * FROM sent_profiles ORDER BY id DESC LIMIT 1")
    SentProfile getLatestProfile();

}